﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace IntegrationTests.Core.Websites
{
	public static class WebsiteFactory
	{
		private static readonly ICollection<WebsiteBase> sites = new List<WebsiteBase>();

		private static WebsiteBase currentWebsite;

		static WebsiteFactory()
		{
			AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
		}

		public static WebsiteBase CurrentWebsite
		{
			get { return (currentWebsite != null && currentWebsite.IsStarted) ? currentWebsite : (currentWebsite = Create()); }
		}

		private static WebsiteBase Create()
		{
			return Create<WebsiteBase>();
		}

		[Obsolete]
		public static T Create<T>() where T : WebsiteBase, new()
		{
			var site = new T();
			sites.Add(site);
			return site;
		}

		private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
		{
			var started = sites.Where(site => site.IsStarted).ToList();
			foreach (WebsiteBase site in started)
				site.Stop();
		}

        public static void StopCurrentWebsite()
        {
        	var website = currentWebsite;
			if (website == null)
				return;

        	if (website.IsStarted)
        		website.Stop();
        	sites.Remove(website);
        	currentWebsite = null;
        }
	}
}